"""
自定义表单组件
"""

from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QFormLayout, QGridLayout,
    QLabel, QLineEdit, QTextEdit, QComboBox, QSpinBox, QDateEdit,
    QCheckBox, QRadioButton, QButtonGroup, QFrame, QScrollArea
)
from PyQt5.QtCore import Qt, QDate
from PyQt5.QtGui import QFont, QIntValidator, QDoubleValidator

class FormWidget(QWidget):
    """自定义表单组件"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        
        self.form_fields = {}
        self.setup_ui()
        self.setup_style()
    
    def setup_ui(self):
        """设置用户界面"""
        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        
        # 创建表单容器
        self.form_container = QWidget()
        self.form_layout = QFormLayout(self.form_container)
        self.form_layout.setSpacing(12)
        self.form_layout.setContentsMargins(20, 20, 20, 20)
        
        scroll_area.setWidget(self.form_container)
        
        # 主布局
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(scroll_area)
    
    def setup_style(self):
        """设置样式"""
        self.setStyleSheet("""
            QLabel {
                color: #333333;
                font-weight: bold;
            }
            QLineEdit, QTextEdit, QComboBox, QSpinBox, QDateEdit {
                padding: 8px 12px;
                border: 1px solid #e0e0e0;
                border-radius: 4px;
                background-color: #ffffff;
                font-size: 12px;
            }
            QLineEdit:focus, QTextEdit:focus, QComboBox:focus, 
            QSpinBox:focus, QDateEdit:focus {
                border-color: #1976d2;
            }
            QCheckBox, QRadioButton {
                spacing: 8px;
            }
            QCheckBox::indicator, QRadioButton::indicator {
                width: 16px;
                height: 16px;
            }
        """)
    
    def add_text_field(self, name, label, placeholder="", required=False, validator=None):
        """添加文本字段"""
        field = QLineEdit()
        field.setPlaceholderText(placeholder)
        
        if validator:
            field.setValidator(validator)
        
        if required:
            label_widget = QLabel(f"{label} *")
            label_widget.setStyleSheet("color: #f44336;")
        else:
            label_widget = QLabel(label)
        
        self.form_layout.addRow(label_widget, field)
        self.form_fields[name] = field
        
        return field
    
    def add_password_field(self, name, label, placeholder="", required=False):
        """添加密码字段"""
        field = QLineEdit()
        field.setPlaceholderText(placeholder)
        field.setEchoMode(QLineEdit.Password)
        
        if required:
            label_widget = QLabel(f"{label} *")
            label_widget.setStyleSheet("color: #f44336;")
        else:
            label_widget = QLabel(label)
        
        self.form_layout.addRow(label_widget, field)
        self.form_fields[name] = field
        
        return field
    
    def add_textarea_field(self, name, label, placeholder="", rows=3):
        """添加多行文本字段"""
        field = QTextEdit()
        field.setPlaceholderText(placeholder)
        field.setFixedHeight(rows * 25)
        
        label_widget = QLabel(label)
        self.form_layout.addRow(label_widget, field)
        self.form_fields[name] = field
        
        return field
    
    def add_combo_field(self, name, label, items=[], required=False):
        """添加下拉选择字段"""
        field = QComboBox()
        field.addItems(items)
        
        if required:
            label_widget = QLabel(f"{label} *")
            label_widget.setStyleSheet("color: #f44336;")
        else:
            label_widget = QLabel(label)
        
        self.form_layout.addRow(label_widget, field)
        self.form_fields[name] = field
        
        return field
    
    def add_spinbox_field(self, name, label, min_value=0, max_value=100, default=0):
        """添加数字输入字段"""
        field = QSpinBox()
        field.setMinimum(min_value)
        field.setMaximum(max_value)
        field.setValue(default)
        
        label_widget = QLabel(label)
        self.form_layout.addRow(label_widget, field)
        self.form_fields[name] = field
        
        return field
    
    def add_date_field(self, name, label, default_date=None):
        """添加日期选择字段"""
        field = QDateEdit()
        field.setCalendarPopup(True)
        field.setDate(default_date or QDate.currentDate())
        
        label_widget = QLabel(label)
        self.form_layout.addRow(label_widget, field)
        self.form_fields[name] = field
        
        return field
    
    def add_checkbox_field(self, name, label, default=False):
        """添加复选框字段"""
        field = QCheckBox(label)
        field.setChecked(default)
        
        self.form_layout.addRow("", field)
        self.form_fields[name] = field
        
        return field
    
    def add_radio_group(self, name, label, options, default_index=0):
        """添加单选按钮组"""
        group_widget = QWidget()
        group_layout = QVBoxLayout(group_widget)
        group_layout.setContentsMargins(0, 0, 0, 0)
        
        button_group = QButtonGroup()
        
        for i, option in enumerate(options):
            radio = QRadioButton(option)
            if i == default_index:
                radio.setChecked(True)
            button_group.addButton(radio, i)
            group_layout.addWidget(radio)
        
        label_widget = QLabel(label)
        self.form_layout.addRow(label_widget, group_widget)
        self.form_fields[name] = button_group
        
        return button_group
    
    def add_separator(self, text=""):
        """添加分隔线"""
        if text:
            separator = QLabel(text)
            separator.setStyleSheet("""
                QLabel {
                    padding: 8px 0px;
                    color: #1976d2;
                    font-weight: bold;
                    border-bottom: 2px solid #1976d2;
                }
            """)
        else:
            separator = QFrame()
            separator.setFrameShape(QFrame.HLine)
            separator.setStyleSheet("""
                QFrame {
                    color: #e0e0e0;
                    max-height: 1px;
                }
            """)
        
        self.form_layout.addRow(separator)
    
    def get_field_value(self, name):
        """获取字段值"""
        field = self.form_fields.get(name)
        if not field:
            return None
        
        if isinstance(field, QLineEdit):
            return field.text()
        elif isinstance(field, QTextEdit):
            return field.toPlainText()
        elif isinstance(field, QComboBox):
            return field.currentText()
        elif isinstance(field, QSpinBox):
            return field.value()
        elif isinstance(field, QDateEdit):
            return field.date().toString("yyyy-MM-dd")
        elif isinstance(field, QCheckBox):
            return field.isChecked()
        elif isinstance(field, QButtonGroup):
            checked_id = field.checkedId()
            if checked_id >= 0:
                button = field.button(checked_id)
                return button.text()
            return None
        
        return None
    
    def set_field_value(self, name, value):
        """设置字段值"""
        field = self.form_fields.get(name)
        if not field:
            return
        
        if isinstance(field, QLineEdit):
            field.setText(str(value))
        elif isinstance(field, QTextEdit):
            field.setPlainText(str(value))
        elif isinstance(field, QComboBox):
            index = field.findText(str(value))
            if index >= 0:
                field.setCurrentIndex(index)
        elif isinstance(field, QSpinBox):
            field.setValue(int(value))
        elif isinstance(field, QDateEdit):
            field.setDate(QDate.fromString(str(value), "yyyy-MM-dd"))
        elif isinstance(field, QCheckBox):
            field.setChecked(bool(value))
        elif isinstance(field, QButtonGroup):
            for i in range(field.buttons().count()):
                button = field.button(i)
                if button.text() == str(value):
                    button.setChecked(True)
                    break
    
    def get_form_data(self):
        """获取表单所有数据"""
        data = {}
        for name in self.form_fields:
            data[name] = self.get_field_value(name)
        return data
    
    def set_form_data(self, data):
        """设置表单数据"""
        for name, value in data.items():
            self.set_field_value(name, value)
    
    def clear_form(self):
        """清空表单"""
        for name, field in self.form_fields.items():
            if isinstance(field, QLineEdit):
                field.clear()
            elif isinstance(field, QTextEdit):
                field.clear()
            elif isinstance(field, QComboBox):
                field.setCurrentIndex(0)
            elif isinstance(field, QSpinBox):
                field.setValue(0)
            elif isinstance(field, QDateEdit):
                field.setDate(QDate.currentDate())
            elif isinstance(field, QCheckBox):
                field.setChecked(False)
            elif isinstance(field, QButtonGroup):
                if field.buttons():
                    field.button(0).setChecked(True)
    
    def validate_required_fields(self):
        """验证必填字段"""
        missing_fields = []
        
        # 检查所有标记为必填的字段
        for i in range(self.form_layout.rowCount()):
            label_item = self.form_layout.itemAt(i, QFormLayout.LabelRole)
            field_item = self.form_layout.itemAt(i, QFormLayout.FieldRole)
            
            if label_item and field_item:
                label = label_item.widget()
                field = field_item.widget()
                
                if label and "*" in label.text():
                    if isinstance(field, QLineEdit) and not field.text().strip():
                        missing_fields.append(label.text().replace(" *", ""))
                    elif isinstance(field, QComboBox) and field.currentText() == "":
                        missing_fields.append(label.text().replace(" *", ""))
        
        return missing_fields